package datastruct.sort;

import java.util.Arrays;

/**
 * @program: DataStructuresAndAlgorithms
 * @description: 归并排序
 * @author: zhang
 * @create: 2020-03-13 15:20
 */
public class MergeSortDemo {

    /**
     * @param null
     * @description: 合并的方法
     * @return:
     * @author: SilverZhang
     * @time: 2020/3/14 17:33
     */
    public static void merge(int[] arr, int left, int middle, int right, int[] temp) {
        int i = left;
        int j = middle + 1;
        int t = 0;  //指向temp数组的当前索引
        //1、先把左右两边的数据按规则拷贝到temp数组，直到左右两边的有序序列，有一边处理完毕为止
        while (i <= middle && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t] = arr[i];
                i += 1;
                t += 1;
            } else {
                temp[t] = arr[j];
                j += 1;
                t += 1;
            }
        }
        //2、把有剩余数据的一边依次全部填充到temp
        while (i <= middle) {
            temp[t] = arr[i];
            i += 1;
            t += 1;
        }
        while (j <= right) {
            temp[t] = arr[j];
            j += 1;
            t += 1;
        }
        //3、将temp数组的元素拷贝到arr
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            arr[tempLeft] = temp[t];
            t += 1;
            tempLeft += 1;
        }
    }

    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int middle = (left + right) / 2;
            //向左递归进行分解
            mergeSort(arr, left, middle, temp);
            //向右递归进行分解
            mergeSort(arr, middle + 1, right, temp);
            //合并
            merge(arr,left,middle,right,temp);
        }
        //先把左右两边的数据
    }

    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[arr.length];

        mergeSort(arr, 0, arr.length-1, temp);

        System.out.println(Arrays.toString(arr));
    }
}